<template>
  <div>
    <el-input
      v-model="searchKey"
      placeholder="请输入名称"
      clearable
      prefix-icon="el-icon-search"
      style="margin-bottom: 20px"
    />

    <el-tree
      ref="tree"
      :data="data"
      :node-key="nodeKey"
      :props="props"
      :default-checked-keys="value"
      :show-checkbox="showCheckbox"
      :check-strictly="checkStrictly"
      :highlight-current="highlightCurrent"
      :default-expand-all="defaultExpandAll"
      @check-change="checkChange"
      @node-click="handleNodeClick"
      :filter-node-method="filterNode"
    >
    </el-tree>
  </div>
</template>
<script>
/**
 * 接口获取数据自动生成element ui Tree组件
 */
import request from "@/utils/request";
import constants from "@/components/zTree/constants";

export default {
  props: {
    /**
     * 类型
     * 对应constants里每一个object的key值
     */
    varient: {
      type: String,
      required: false,
    },
    /**
     * 初始值
     */
    value: {
      type: [Array],
      default: () => [],
    },
    /**
     * @ignore
     * 详见element ui
     */
    nodeKey: {
      type: String,
      default: "",
    },
    /**
     * @ignore
     * 详见element ui
     */
    showCheckbox: {
      type: Boolean,
      default: false,
    },
    /**
     * @ignore
     * 详见element ui
     */
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    highlightCurrent: {
      type: Boolean,
      default: true,
    },
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
    /**
     * @ignore
     * 详见element ui
     */
    props: {
      type: Object,
      default: () => ({
        children: "children",
        label: "label",
      }),
    },
    extraData: {
      type: [Object, Array],
      default: () => [],
    },
  },
  data() {
    return {
      searchKey: "",
      data: [],
    };
  },
  watch: {
    searchKey(val) {
      this.$refs.tree.filter(val);
    },
    value: {
      handler(val) {
        if (val) {
          this.data = this.value;
        }
      },
      immediate: true,
    },
  },
  created() {
    if (!this.varient) {
      // setTimeout(() => {
      //   this.data = this.value;
      // }, 1000);
    } else {
      this.getList();
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    async getList(val) {
      const url = constants[this.varient];
      const res = await request({
        url,
        method: "get",
        params: {
          name: val,
        },
      });
      this.data = [...this.extraData, ...res.data];
    },
    checkChange(value) {
      this.$emit("input", this.$refs.tree.getCheckedKeys());
    },
    handleNodeClick(data) {
      this.$emit("handleNodeClick", data);
    },
  },
};
</script>
